import { Card, Button, Input } from "antd";
import React, { useRef, useState } from "react";

import UploadImgX from "@/components/addContent/uploadx";

import { uploadLogoInfo } from "@/api/api_client_home";

interface ChildMethods {
  handleUpload: () => void;
}

function CardLogo() {
  const childRef = useRef<ChildMethods>(null); // 创建一个 ref 来引用子组件

  const [title, setTitle] = useState<string>(""); // 头像编号

  // 提交表单
  const handleImageUpload = async () => {
    if (childRef.current) {
      const result = childRef.current.handleUpload();
      return result;
    } else {
      return [];
    }
  };

  const getTitle = (e: React.ChangeEvent<HTMLInputElement>) => {
    // console.log(e.target.value);
    setTitle(e.target.value);
  };

  const uploadInfo = async () => {
    const img_url: string[] = await handleImageUpload();

    const data = {
      title: title,
      img_url: img_url[0],
    };

    try {
      const res = await uploadLogoInfo(data);
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div>
      <Card
        extra={
          <Input
            onChange={getTitle}
            style={{ width: 120 }}
            placeholder="头像编号"
          />
        }
        title="头像上传"
        bordered={false}
        style={{ width: 300 }}
        actions={[
          <Button onClick={uploadInfo} type="link" block>
            上传
          </Button>,
        ]}
      >
        <UploadImgX ref={childRef} type="logo" />
      </Card>
    </div>
  );
}

export default CardLogo;
